import React, {useEffect, useRef, useState} from "react";
import {ProColumns, ProTable} from "@ant-design/pro-table";
import {OweLogItem} from "@/pages/OweLogs/data";
import {message, Popconfirm, Tag} from "antd";
import {ArrowRightOutlined, CheckOutlined, DeleteOutlined, EditOutlined} from "@ant-design/icons";
import {ActionType} from "@ant-design/pro-table";
import {deleteOweLog, queryOweLog, updateOweLog, updateOwePaybackLog} from "@/pages/OweLogs/service";
import dayjs from "dayjs";
import PaybackForm from "@/pages/OweLogs/components/PaybackForm";
import PaybackLogForm from "@/pages/OweLogs/components/PaybackLogForm";
import UpdateForm from "@/pages/OweLogs/components/UpdateForm";
import Style from './style.less'

/**
 * 删除节点
 *
 * @param record
 */
const handleSingleRemove = async (record: OweLogItem) => {
  const hide = message.loading('正在删除');
  try {
    const res = await deleteOweLog({
      key: record.id,
    });
    hide();
    if (res) {
      if (res.status === 'done') {
        message.success(res.message);
        return true;
      } else {
        message.error(res.message);
        return false;
      }
    } else {
      message.error('请求超时，请稍后重试');
      return false;
    }
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

/**
 * 更新节点
 *
 * @param fields
 * @param currentRow
 */

const handlePaybackLogUpdate = async (fields: any, currentRow?: OweLogItem) => {
  const hide = message.loading('正在记录。。。。。。');

  try {
    const res = await updateOwePaybackLog({
      id: currentRow?.id,
      ...fields,
    });
    if(res && res.status === "done" ){
      hide();
      message.success(res.message);
      return true;
    }else {
      hide()
      message.error(res.message);
      return false;
    }
  } catch (error) {
    hide();
    message.error('记录失败，请重试！' + error);
    return false;
  }
};
/**
 * 流水更新节点
 *
 * @param fields
 * @param currentRow
 */

const handleLogUpdate = async (fields: any, currentRow?: OweLogItem) => {
  const hide = message.loading('正在修改。。。。。。');

  try {
    const res = await updateOweLog({
      id: currentRow?.id,
      ...fields,
    });
    if(res && res.status === "done" ){
      hide();
      message.success(res.message);
      return true;
    }else {
      hide()
      message.error(res.message);
      return false;
    }
  } catch (error) {
    hide();
    message.error('修改失败，请重试！' + error);
    return false;
  }
};

export type Props = {
  update: boolean;
};

const OweLogs: React.FC<Props> = (props: {update: boolean}) => {
  const actionRef = useRef<ActionType>();

  // 还钱窗口
  const [currentRow, setCurrentRow] = useState<OweLogItem>();
  const [paybackModalVisable, handlePaybackModalVisable] = useState<boolean>(false)
  const [paybackLogModalVisable, handlePaybackLogModalVisable] = useState<boolean>(false)

  /** 更新窗口的弹窗 */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

  // 更新流水
  useEffect(() => {
    actionRef.current?.reload()
  }, [props.update]);
  const columns: ProColumns<OweLogItem>[] = [
    {
      title: "id",
      dataIndex: "id",
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: "日期",
      dataIndex: "date",
      valueType: "text",
      align: "center",
      hideInSearch: true,
      width: 100,
      render: (_, record) =>{
        if (record.date){
          return record.date
        }return null
      }
    },
    {
      title: "时间",
      dataIndex: "time",
      valueType: "time",
      align: "center",
      hideInSearch: true,
      width: 50,
      render: (_, record)=>(
        dayjs(record.oweTime).format("HH:mm")
      )
    },
    {
      title: "跟谁借",
      dataIndex: "toWho",
      valueType: "text",
      align: "center",
      hideInSearch: true,
      render: (_, record)=>(
        <Tag color={"red"}>{record.toWho}</Tag>
      )
    },
    {
      title: "借入金额",
      dataIndex: "oweMoney",
      valueType: "money",
      align: "right",
      hideInSearch: true,
      className: Style.inColor
    },
    {
      title: "已还金额",
      dataIndex: "paybackMoney",
      valueType: "money",
      align: "right",
      hideInSearch: true,
      className: Style.outColor
    },
    {
      title: "状态",
      align: "center",
      render:(_, record)=>{
        if (record.done){
          return <Tag color={"green"}><CheckOutlined/> 已结清</Tag>
        }else {
          return <Tag color={"red"}><ArrowRightOutlined/> 未结清</Tag>
        }
      }
    },
    {
      title: "备注",
      dataIndex: "remark",
      valueType: "text",
      align: "left",
    },
    {
      title: "",
      valueType: "option",
      align: "right",
      width: 112,
      render: (_, record)=>[
        <a
          title={"还钱"}
          key={"lendLog"}
          style={{color: "blue"}}
          onClick={()=>{
            setCurrentRow(record)
            handlePaybackModalVisable(true)
          }}
        >还</a>,
        <a
          title={"还款记录"}
          key={"lendLog"}
          style={{color: "green"}}
          onClick={()=>{
            setCurrentRow(record)
            handlePaybackLogModalVisable(true)
          }}
        >记录</a>,
        <a
          style={{color: "gray"}}
          key={"update"}
          title={"修改流水"}
          onClick={()=>{
            setCurrentRow(record)
            handleUpdateModalVisible(true)
          }}
        ><EditOutlined/></a>,
        <Popconfirm key="popconfirm" title={`确认删除吗?`} okText="是" cancelText="否" onConfirm={async () => {
          const success = await handleSingleRemove(record);
          if (success) {
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}>
          <a style={{color: "gray"}} ><DeleteOutlined /></a>
        </Popconfirm>
      ]
    },
  ];
  return (
    <>
      <ProTable
        scroll={{ y: `calc(100vh - 260px)`, x: `max-content` }}
        defaultSize={"small"}
        actionRef={actionRef}
        columns={columns}
        rowKey={"id"}
        search={false}
        headerTitle={<b style={{color:"red"}}>借入流水</b>}
        options={false}
        request={queryOweLog}
        pagination={{defaultPageSize: 10, pageSizeOptions:[10, 20, 100, 1000, 10000], showSizeChanger: true}}
      />
      <PaybackForm
        onCancel={()=>{
          handlePaybackModalVisable(false)
          setCurrentRow(undefined)
        }}
        onSubmit={async (value: any)=>{
          const success = await handlePaybackLogUpdate(value, currentRow as OweLogItem);
          if (success){
            handlePaybackModalVisable(false)
            setCurrentRow(undefined)
            actionRef.current?.reload()
          }
        }}
        modalVisible={paybackModalVisable}
        values={currentRow || {}}
      />
      <PaybackLogForm
        onCancel={()=>{
          handlePaybackLogModalVisable(false)
          setCurrentRow(undefined)
          actionRef.current?.reload()
        }}
        onSubmit={async () =>{
          handlePaybackLogModalVisable(false)
          setCurrentRow(undefined)
          actionRef.current?.reload()
        }}
        modalVisible={paybackLogModalVisable}
        values={currentRow || {}}
      />
      <UpdateForm
        onCancel={()=>{
          handleUpdateModalVisible(false)
          setCurrentRow(undefined)
          actionRef.current?.reload()
        }}
        onSubmit={async (value)=>{
          const success = await handleLogUpdate(value, currentRow);
          if (success){
            handleUpdateModalVisible(false)
            setCurrentRow(undefined)
            // 更新数据
            actionRef.current?.reload()
          }
        }}
        modalVisible={updateModalVisible}
        values={currentRow || {}}
      />
    </>
  )
}
export default OweLogs;
